package com.gpj.netty.demo.model;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Consumer;

/**
 * @className STDNettyServer
 * @description TODO
 * @author GPJ
 * @date 2021/3/3 14:19
 * @version 1.0
 **/
@Slf4j
public class STDNettyServer {
	public static void run(Consumer<SocketChannel> consumer){
		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
		NioEventLoopGroup workGroup = new NioEventLoopGroup();

		try {
			ServerBootstrap bootstrap = new ServerBootstrap()
					.group(bossGroup, workGroup)
					.channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 100)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel socketChannel) {
							consumer.accept(socketChannel);
						}
					});
			ChannelFuture future = bootstrap.bind(9000).sync();
			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			log.error("netty服务端启动失败:{}", e.getMessage(), e);
		}finally {
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
	}
}
